<template>
  <!-- 覆盖waike样式 -->
  <waike title="注册" class="register">
    <template #form>
      <router-link to="/">返回登录</router-link>
      <div class="login-from">
        <el-form
          :model="ruleForm3"
          status-icon
          :rules="rules3"
          ref="ruleForm3"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户账号" prop="uname">
            <el-input
              type="text"
              auto-complete="off"
              placeholder="请输入用户名/手机号"
              v-model="ruleForm3.uname"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="upwd">
            <el-input
              type="password"
              auto-complete="off"
              placeholder="请输入密码"
              v-model="ruleForm3.upwd"
            ></el-input>
          </el-form-item>

          <el-form-item label="确认密码" prop="checkupwd">
            <el-input
              type="password"
              auto-complete="off"
              placeholder="请再次输入密码"
              v-model="ruleForm3.checkupwd"
            ></el-input>
          </el-form-item>

          <el-form-item label="手机号码" prop="uphone">
            <el-input
              type="text"
              auto-complete="off"
              placeholder="请输入手机号码"
              v-model="ruleForm3.uphone"
            ></el-input>
          </el-form-item>

          <el-form-item label="用户类型" prop="utype">
            <el-select v-model="ruleForm3.utype" style="width: 100%">
              <el-option label="请选择用户类型" value=""></el-option>
              <el-option label="学生" value="0"></el-option>
              <el-option label="老师" value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="用户性别" prop="usex">
            <el-select v-model="ruleForm3.usex" style="width: 100%">
              <el-option label="请选择用户性别" value=""></el-option>
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="出生日期" prop="ubirthday">
            <el-input
              type="date"
              auto-complete="off"
              placeholder="请选择出生日期"
              v-model="ruleForm3.ubirthday"
            ></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="uemail">
            <el-input
              type="email"
              auto-complete="off"
              placeholder="请输入邮箱"
              v-model="ruleForm3.uemail"
            ></el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="uyzm">
            <el-input
              type="text"
              auto-complete="off"
              placeholder="请输入验证码"
              v-model="ruleForm3.uyzm"
              ><el-button :disabled="disabled" slot="append" @click="send"
                >发送验证码</el-button
              ></el-input
            >
          </el-form-item>

          <div class="button">
            <el-button type="primary" @click="submitForm('ruleForm3')"
              >注册</el-button
            >
            <el-button type="primary" @click="resetForm('ruleForm3')"
              >重置</el-button
            >
          </div>
        </el-form>
      </div>
    </template>
  </waike>
</template>

<script>
import waike from "@/components/waike.vue"; //@就相当于views文件夹下
import axios from "axios";
import qs from "qs";
import { Message } from "element-ui";
export default {
  components: { waike },
  watch: {
    //深度监听一个对象的某个值发生变化
    "ruleForm3.uname": {
      deep: true,
      handler(val, oldval) {
        //发起请求验证输入的用户名是否存在
        axios
          .post("/v1/users/checkname", `username=${val}`)
          .then((result) => {
            this.unameStatus = result.data.status;
          })
          .catch((err) => {
            console.log(err);
          });
      },
    },

    //深度监听一个对象的某个值发生变化
    "ruleForm3.uphone": {
      deep: true,
      handler(val, oldval) {
        //发起请求验证输入的手机号是否存在
        axios
          .post("/v1/users/checkphone", `phone=${val}`)
          .then((result) => {
            this.uphoneStatus = result.data.status;
          })
          .catch((err) => {
            console.log(err);
          });
      },
    },

    //深度监听一个对象的某个值发生变化
    "ruleForm3.uemail": {
      deep: true,
      handler(val, oldval) {
        //发起请求验证输入的邮箱是否存在
        axios
          .post("/v1/users/checkemail", `email=${val}`)
          .then((result) => {
            this.uemailStatus = result.data.status;
          })
          .catch((err) => {
            console.log(err);
          });
      },
    },
  },
  data() {
    var validateName = (rule, value, callback) => {
      let reg = /[aA][vV]/; //敏感词
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (this.unameStatus == 200) {
        callback(new Error("该用户名已存在"));
      } else if (/^\d+$/.test(value)) {
        callback(new Error("用户名不能为纯数字"));
      } else if (value.search(reg) != -1) {
        callback(new Error("有敏感词"));
      } else {
        callback();
      }
    };

    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 8 || /^\d+$/.test(value)) {
        callback(new Error("密码不能为纯数字,且不能小于8位"));
      } else {
        callback();
      }
    };

    var validateCheckupwd = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm3.upwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    var validateUphone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (this.uphoneStatus == 200) {
        callback(new Error("该手机号已存在"));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };

    var validateType = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择用户类型"));
      } else {
        callback();
      }
    };

    var validateSex = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择用户性别"));
      } else {
        callback();
      }
    };

    var validateBirthday = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择出生日期"));
      } else {
        callback();
      }
    };

    var validateUemail = (rule, value, callback) => {
      if (value === "") {
        this.disabled = true; //防止用户反复操作,如果不设置，用户本来输入正确了，此时按钮解除禁用，
        //然后突然删除又变错误了，此时要禁用按钮
        callback(new Error("请输入邮箱"));
      } else if (this.uemailStatus == 200) {
        this.disabled = true;
        callback(new Error("该邮箱已存在"));
      } else if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
        this.disabled = true;
        callback(new Error("请输入正确的邮箱"));
      } else {
        this.disabled = false; //输入正确解除禁用
        callback();
      }
    };

    var validateYzm = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else if (value != this.ruleForm3.code) {
        callback(new Error("验证码错误"));
      } else {
        callback();
      }
    };
    return {
      unameStatus: "",
      uphoneStatus: "",
      uemailStatus: "",
      disabled: true,
      ruleForm3: {
        uname: "",
        upwd: "",
        checkupwd: "",
        uphone: "",
        utype: "",
        usex: "",
        ubirthday: "",
        uemail: "",
        uyzm: "",
        code: "",
      },
      rules3: {
        uname: [{ validator: validateName, trigger: "blur" }],
        upwd: [{ validator: validatePass, trigger: "blur" }],
        checkupwd: [{ validator: validateCheckupwd, trigger: "blur" }],
        uphone: [{ validator: validateUphone, trigger: "blur" }],
        utype: [{ validator: validateType, trigger: "change" }],
        usex: [{ validator: validateSex, trigger: "change" }],
        ubirthday: [{ validator: validateBirthday, trigger: "change" }],
        uemail: [{ validator: validateUemail, trigger: "blur" }],
        uyzm: [{ validator: validateYzm, trigger: "blur" }],
      },
    };
  },

  methods: {
    //登录
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios({
            method: "post",
            url: "/v1/users/register",
            data: qs.stringify({
              username: this.ruleForm3.uname,
              password: this.ruleForm3.upwd,
              phone: this.ruleForm3.uphone,
              type: this.ruleForm3.utype,
              sex: this.ruleForm3.usex,
              birthday: this.ruleForm3.ubirthday,
              email: this.ruleForm3.uemail,
            }),
            headers: {
              "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
            },
          })
            .then((result) => {
              if (result.data.status == 200) {
                Message.success({
                  showClose: true,
                  message: "注册成功",
                  type: "success",
                });
                this.$router.push("/");
              } else {
                Message.error({
                  showClose: true,
                  message: "注册失败",
                  type: "error",
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    //发送验证码axios,多请求操作
    sendaxios() {
      axios
        .get("/v1/users/email", {
          params: {
            email: this.ruleForm3.uemail,
          },
        })
        .then((res) => {
          // console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });

      axios
        .get("/v1/users/emailyzm", {
          params: {
            email: this.ruleForm3.uemail,
          },
        })
        .then((res) => {
          // console.log(res);
          this.ruleForm3.code = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //点击发送验证码
    send(e) {
      this.sendaxios();
      let time = 60; //定义60秒的倒计时
      let that = this; //因为this在函数中指向window，所以定义that接收
      function subs() {
        time--;
        e.target.innerHTML = `请${time}秒后再试`;
        if (time === 0) {
          clearInterval(mytime);
          e.target.innerHTML = `发送验证码`;
          that.disabled = false; //按键可用
        } else {
          that.disabled = true; //按键不可用
        }
      }
      //设置一个定时，一秒执行一次
      let mytime = setInterval(function () {
        subs();
      }, 1000);
    },
  },
};
</script>

<style lang="scss">
.register {
  .login-content {
    width: 400px;
    height: 100vh;
    overflow: auto;
    margin: auto;
    background: rgba(255, 255, 255, 1);
    position: absolute;
    left: 0;
    right: 0;
    top: 50%;
    font-size: 12px;
    transform: translateY(-50%);
  }
}
</style>